package service

import (
	"fmt"
	"github.com/casbin/casbin/v2"
	"github.com/casbin/redis-adapter/v2"
	"go.uber.org/zap"
	"jwgin/model/mysql"
	"log"
)

func InitCasbin() {
	var a *redisadapter.Adapter
	if len(Conf.Redis.Password) > 0 {
		a = redisadapter.NewAdapterWithPassword("tcp", Conf.Redis.Addr, Conf.Redis.Password)
	} else {
		a = redisadapter.NewAdapter("tcp", Conf.Redis.Addr)
	}

	e, err := casbin.NewEnforcer("conf/model.conf", a)
	if err != nil {
		panic(err)
	}
	err = e.LoadPolicy()
	if err != nil {
		log.Fatal()
	}
	E = e
	zap.L().Info("Casbin 启动ok..")
	CasbinLoad()
}

//重载 暴露
func CasbinLoad() {
	role := []mysql.Roles{}
	G.Find(&role)
	for _, v := range role {
		if v.RoleApiList == "" {
			continue
		}
		api := []mysql.PermissionApi{}
		sql := fmt.Sprintf("api_id in (%s)", v.RoleApiList)
		G.Where(sql).Find(&api)
		for _, item := range api {
			id := fmt.Sprintf("%v", v.RuleId)
			E.AddPolicy(id, item.ApiPath, item.ApiMethod)
		}
	}
}
